<!-- 分享物流码 -->
<template>
  <view class="share_layout_box">
    <canvas
      class="myCanvas test"
      :style="'width:' + myCanvasWidth + 'px;height:' + myCanvasHeight + 'px'"
      canvas-id="queryLogisticsShareId"
    ></canvas>
  </view>
</template>
<script>
// let canvasData = { // 图片生成参数
//   page: '/pages/index/index', // 二维码地址
//   userAvatar: 'https://image.qqpyyds.com/user/avatar/1448144136114941954', // 用户头像
//   userNickname: '廖志林',  // 用户昵称
// }
// this.$refs.childQueryLogisticsShare.sharePosterFrends(canvasData)
// import { writeFile, removeSave } from '@/api/baseConvert'
import share from "@/api/share.js"
export default {
  data () {
    return {
      myCanvasWidth: 280,
      myCanvasHeight: 312,
      dpiMun: 3,
    }
  },
  created () {
    this.myCanvasWidth = this.myCanvasWidth*this.dpiMun
    this.myCanvasHeight = this.myCanvasHeight*this.dpiMun
  },
  methods: {
    async sharePosterFrends(data) {
      wx.showLoading({
        title: '生成中...',
        mask: true
      })
      let _this = this
      let _data = data
      let paramMap = {
        page: _data?.page ?? 'pages/index/index',
        ..._data.options,
        isHyaline: true,
        lineColor: {'r':253,'g':253,'b':253},
      }
      share.getSunCode(paramMap).then(async (res_) => {
        if (res_.code == 200) {
          let pam = {
            ..._data,
            QRCode: res_.data
          }
          console.log(pam)
          await _this.createdCode(pam)
          let shareData = {}
          wx.canvasToTempFilePath({
            canvasId: 'queryLogisticsShareId',
            fileType: 'jpg',
            width: _this.myCanvasWidth,
            height: _this.myCanvasHeight,
            destWidth: _this.myCanvasWidth * 2,
            destHeight: _this.myCanvasHeight * 2,
            success: async (res) => {
              shareData = {
                code: '200',
                msg: '绘制成功！',
                url: res.tempFilePath
              }
              console.log(shareData,'绘制成功')
              // _this.$store.commit('POSTER_SHARING_DATA', shareData)
              _this.$emit('posterShareSuccess', shareData)
              wx.hideLoading()
            },
            fail: function (res) {
              console.log('绘制失败')
              wx.hideLoading()
            }
          },_this)
          // removeSave() // 先删除在添加
          // writeFile(res_.data).then(async (img)=>{
          // }).catch(e=>{
          //   console.log(e)
          //   wx.hideLoading()
          // })
        }
      })
    },
    // 开始绘图
    createdCode (data) {
      console.log(data)
      const _this = this
      let fromData = data
      return new Promise(resolve => {
        exec()
        async function exec () {
          const ctx = wx.createCanvasContext('queryLogisticsShareId', _this) // 绘图上下文
          ctx.save()
          _this.handleBorderRect(ctx, 0, 0, _this.myCanvasWidth, _this.myCanvasHeight, 8*_this.dpiMun, '#E44435')
          _this.handleBorderRect(ctx, 10*_this.dpiMun, 10*_this.dpiMun, _this.myCanvasWidth-(20*_this.dpiMun), _this.myCanvasHeight-(20*_this.dpiMun), 4*_this.dpiMun, '#ffffff')
          ctx.clip()
          ctx.setFontSize(18*_this.dpiMun)
          ctx.setFillStyle('#323233')
          ctx.fillText('长按识别查询物流', 68*_this.dpiMun, 46*_this.dpiMun, 150*_this.dpiMun)
          ctx.setFontSize(12*_this.dpiMun)
          ctx.setFillStyle('#323233')
          ctx.fillText('快去看看，你团购的商品到哪里了', 50*_this.dpiMun, 66*_this.dpiMun, 200*_this.dpiMun)
          ctx.restore()
          await _this.drawImg(fromData.QRCode, ctx, _this.myCanvasWidth/2-(40*_this.dpiMun), 116*_this.dpiMun, 80*_this.dpiMun, 80*_this.dpiMun)
          ctx.restore()
          ctx.save()
          ctx.beginPath()
          ctx.strokeStyle = '#fff'
          ctx.arc(_this.myCanvasWidth/2,156*_this.dpiMun,18*_this.dpiMun,0,2*Math.PI)
          ctx.fill()
          ctx.clip()
          await _this.drawImg(fromData.userAvatar, ctx, _this.myCanvasWidth/2-(18*_this.dpiMun), 138*_this.dpiMun, 36*_this.dpiMun, 36*_this.dpiMun)
          ctx.restore()
          ctx.save()
          ctx.setFontSize(14*_this.dpiMun)
          ctx.setFillStyle('#323233')
          let userNicknameStr = fromData.userNickname.length>16?fromData.userNickname.slice(0,15)+'...':fromData.userNickname
          ctx.fillText(userNicknameStr, (_this.myCanvasWidth-ctx.measureText(userNicknameStr).width)/2, 224*_this.dpiMun, _this.myCanvasHeight-(20*_this.dpiMun))
          ctx.setFontSize(12*_this.dpiMun)
          ctx.setFillStyle('#969799')
          let tipsStr = '快递小哥正在快马加鞭，期待你的好评哦'
          ctx.fillText(tipsStr, (_this.myCanvasWidth-ctx.measureText(tipsStr).width)/2, 270*_this.dpiMun, _this.myCanvasHeight-(20*_this.dpiMun))
          ctx.restore()
          ctx.draw(false, () => {
            resolve()
          })
        }
      })
    },
    // 画4个圆角
    handleBorderRect (ctx, x, y, w, h, r, color) {
      ctx.beginPath()
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI)
      ctx.moveTo(x + r, y)
      ctx.lineTo(x + w - r, y)
      ctx.lineTo(x + w, y + r)
      // 右上角
      ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI)
      ctx.lineTo(x + w, y + h - r)
      ctx.lineTo(x + w - r, y + h)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
      ctx.lineTo(x + r, y + h)
      ctx.lineTo(x, y + h - r)
      // 左下角
      ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI)
      ctx.lineTo(x, y + r)
      ctx.lineTo(x + r, y)
      ctx.fillStyle = color
      ctx.fill()
      ctx.closePath()
    },
    // 文字自动换行
    wordsWrap (ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
      let lineWidth = 0
      let lastSubStrIndex = 0
      for (let i = 0; i < name.length; i++) {
        lineWidth += ctx.measureText(name[i]).width
        if (lineWidth > maxWidth) {
          ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY)
          srartY += wordsHight
          lineWidth = 0
          lastSubStrIndex = i
        }
        if (i === name.length - 1) {
          ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY)
        }
      }
    },
    // 绘制远程网络图片
    async drawImg (url, ctx, startX, startY, width, height) {
      let _this = this
      return new Promise(resolve => {
        exec()
        async function exec () {
          wx.getImageInfo({
            src: url,
            success: function (res) {
              const filePath = res.path
              ctx.drawImage(filePath, startX, startY, width, height)
              resolve()
            },
            fail: function (err) {
              console.log(err)
            },
            complete: function (err) {
              console.log(err)
            }
          })
        }
      })
    }
  },
}
</script>
<style scoped lang="scss">
.share_layout_box {
  position: fixed;
  left: -1000px;
  top: -1000px;
  // z-index: 999;
}
</style>